package com.rrkd.handler;


import java.io.File;
import java.io.IOException;

import com.rrkd.model.RequestFile;
import com.rrkd.model.ResponseFile;
import com.rrkd.util.FileTransferProperties;
import com.rrkd.util.FileUtils;
import com.rrkd.util.SM3;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class FileCheckSM3Handler extends ChannelInboundHandlerAdapter {
	private RequestFile request;
	/**
	 * 文件默认存储地址
	 */
	private static String file_dir = FileTransferProperties.getString(
			"file_write_path", "/");

	
	@Override
	public void channelRead(ChannelHandlerContext ctx,Object msg){
		if(msg instanceof RequestFile){
			request=(RequestFile) msg;
			ResponseFile reponse=new ResponseFile();
			//服务端文件路径
			String filedir = request.getUploadDestPath() + File.separator
					+ request.getFile_name() + request.getFile_type();
			 if(request.getUpload_status() != null
						&& request.getUpload_status().equals("Scheduledtime")&&request.getSM3MatchResult()==null){
					File localFile = new File(filedir);
					String sm3=getSm3(localFile);
					
					if(request.getSM3().equals(sm3)){
						//sm3的值一致，则不用重新发送
						request.setSM3MatchResult("MATCH");
						ctx.writeAndFlush(request);
//						reponse.setResult("MATCH");
//						ctx.writeAndFlush(reponse);
					}else{
						//reponse.setResult("NOT_MATCH");
						request.setSM3MatchResult("NOT_MATCH");
						ctx.writeAndFlush(request);
						deleteFile(localFile);
					}
			 }else{
				 //ctx.writeAndFlush(request);
				 ctx.fireChannelRead(request);
			 }
			 
		
		}
	}
	
	
	public void deleteFile(File file){
		if(file.exists()){
			file.delete();
			System.out.println(file.delete());
		}
	}
	public String getSm3(File localfile){
		String sm3="";
		try {
			sm3=SM3.getFileSM3String(localfile);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sm3;
	}


}
